<template>
    <div class="common-box" v-if="boxIsShow">
        <div class="common-content-box">
            <div class="content-table-box">
                <div class="content_table_title_box">
                    <img src="@/assets/icon-data.png" class="content_table_title_icon">
                    <div class="content_table_title">订单列表</div>
                </div>
                <div class="table_search_box">
                    <el-form :inline="true" :model="searchForm" ref="searchForm" class="demo-form-inline">
                        <el-form-item label="订单编号" style="margin-bottom: 0;">
                            <el-input v-model="searchForm.orderId" placeholder="请输入订单编号" size="small "></el-input>
                        </el-form-item>
                        <el-form-item label="运单号" style="margin-bottom: 0;">
                          <el-input v-model="searchForm.trackingNo" placeholder="请输入订单编号" size="small "></el-input>
                        </el-form-item>
                        <el-form-item label="报单时间" style="margin-bottom: 0;">
                            <el-date-picker
                              size="small "
                              v-model="searchForm.getPdfTime"
                              @change="handleDateChange1"
                              type="datetimerange"
                              range-separator="-"
                              start-placeholder="开始日期"
                              end-placeholder="结束日期"
                              value-format="yyyy-MM-dd HH:mm:ss">
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item label="下载时间" style="margin-bottom: 0;">
                          <el-date-picker
                            size="small "
                            v-model="searchForm.downloadTime"
                            @change="handleDateChange2"
                            type="datetimerange"
                            range-separator="-"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            value-format="yyyy-MM-dd HH:mm:ss">
                          </el-date-picker>
                        </el-form-item>
                        <el-form-item label="创建时间" style="margin-bottom: 0;">
                          <el-date-picker
                            size="small "
                            v-model="searchForm.createTime"
                            @change="handleDateChange3"
                            type="datetimerange"
                            range-separator="-"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            value-format="yyyy-MM-dd HH:mm:ss">
                          </el-date-picker>
                        </el-form-item>
                        <el-form-item label="是否下载" style="margin-bottom: 0;">
                            <el-select v-model="searchForm.isDownload" placeholder="请选择" size="small ">
                              <el-option label="未下载" value="0"></el-option>
                              <el-option label="已下载" value="1"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item style="margin-bottom: 0;">
                            <el-button type="primary" @click="search" size="small">查询</el-button>
                            <el-button @click="resetForm" size="small">重置</el-button>
                        </el-form-item>
                    </el-form>
                </div>
                <div style="width: 96%;margin-left:2%">
                  <el-menu :default-active="searchForm.orderStatus" class="el-menu-demo" mode="horizontal" @select="handleSelect">
                    <el-menu-item index="0">全部</el-menu-item>
                    <el-menu-item index="1">待付款</el-menu-item>
                    <el-menu-item index="2">待发货(已付款)</el-menu-item>
                    <el-menu-item index="3">已发货</el-menu-item>
                    <el-menu-item index="4">已完成</el-menu-item>
                    <el-menu-item index="5">售后中</el-menu-item>
                    <el-menu-item index="6">已取消</el-menu-item>
                  </el-menu>
                </div>
                <div class="gn_btn_div">
                  <!-- <el-button type="primary" size="small" icon="el-icon-download">订单导出</el-button> -->
                  <el-button type="primary" size="small" icon="el-icon-share" v-if="searchForm.orderStatus==2||searchForm.orderStatus==3" @click="BatchDownload" v-loading.fullscreen.lock="fullscreenLoading">订单下载</el-button>
                  <el-button type="warning" size="small" icon="el-icon-share" v-if="searchForm.orderStatus==2" @click="BatchGetTNo">获取运单号</el-button>
                </div>
                <div class="table_box">
                    <el-table
                        border
                        :data="tableData"
                        style="width: 100%;"
                        height="92%"
                        @selection-change="handleSelectionChange">
                        <el-table-column
                          fixed
                          type="selection"
                          width="55"
                          align="center">
                        </el-table-column>
                        <el-table-column
                        fixed
                        prop="orderId"
                        label="订单编号"
                        width="200"
                        align="center">
                        </el-table-column>
                        <el-table-column
                        label="订单状态"
                        width="180"
                        align="center">
                        <template slot-scope="scope">
                          <div class="line-break">
                            <span>{{ scope.row.orderStatus==1?'待付款':scope.row.orderStatus==2?'待发货（已付款）': scope.row.orderStatus==3?'已发货（待收货）':scope.row.orderStatus==4?'已完成':scope.row.orderStatus==5?'售后中':'已取消'}}</span>
                            <span>{{scope.row.afterStatus==2?'退款完成':scope.row.afterStatus==3?'拒绝退款':scope.row.afterStatus==4?'正在退款中':''}}</span>
                          </div>
                        </template>
                        </el-table-column>
                        <el-table-column
                        prop="yujifahuo"
                        label="预计发货时间"
                        width="160"
                        align="center">
                        </el-table-column>
                        <el-table-column
                        prop="downloadTime"
                        label="下载时间"
                        width="160"
                        align="center">
                        </el-table-column>
                        <el-table-column label="报单信息" align="center">
                          <el-table-column
                          prop="getPdfTime"
                          label="报单时间"
                          width="160"
                          align="center">
                          </el-table-column>
                          <el-table-column
                          prop="pdfNum"
                          label="文件数"
                          width="90"
                          align="center">
                          </el-table-column>
                          <el-table-column
                          prop="pdfSize"
                          label="文件大小"
                          width="90"
                          align="center"
                          :show-overflow-tooltip=true>
                          </el-table-column>
                          <el-table-column
                          prop="pdfYeshu"
                          label="图片数"
                          width="90"
                          align="center">
                          </el-table-column>
                        </el-table-column>
                        <el-table-column
                        prop="trackingNo"
                        label="运单号"
                        width="150"
                        align="center">
                        </el-table-column>
                        <el-table-column label="收货信息" align="center">
                          <el-table-column
                          prop="receivePro"
                          label="省"
                          width="100"
                          align="center"
                          :show-overflow-tooltip=true>
                          </el-table-column>
                          <el-table-column
                          prop="receiveCity"
                          label="市"
                          width="100"
                          align="center"
                          :show-overflow-tooltip=true>
                          </el-table-column>
                          <el-table-column
                          prop="receiveArea"
                          label="区"
                          width="100"
                          align="center"
                          :show-overflow-tooltip=true>
                          </el-table-column>
                          <el-table-column
                          prop="receiveAddress"
                          label="地址"
                          width="100"
                          align="center"
                          :show-overflow-tooltip=true>
                          </el-table-column>
                          <el-table-column
                          prop="uname"
                          label="姓名"
                          width="100"
                          align="center">
                          </el-table-column>
                          <el-table-column
                          prop="utell"
                          label="电话"
                          width="150"
                          align="center">
                          </el-table-column>
                        </el-table-column>
                        <el-table-column
                        prop="lastUpdateTime"
                        label="最后操作时间"
                        width="160"
                        align="center">
                        </el-table-column>
                        
                        
                        <!-- <el-table-column
                        label="制作产物"
                        width="100">
                        <template slot-scope="scope">
                          <el-button @click="lookPdf(scope.row.orderId)" type="text" size="small">下载</el-button>
                        </template>
                        </el-table-column> -->
                        <el-table-column
                        fixed="right"
                        label="操作"
                        min-width="100"
                        align="center">
                        <template slot-scope="scope">
                          <el-button @click="toDesc(scope.row.orderId)" type="text" icon="el-icon-view" size="small">详情</el-button>
                          <!-- <el-button @click="openTip(scope.row.orderId,3)" type="text" size="small" v-if="scope.row.orderStatus==2">发货</el-button> -->
                          <el-button @click="toPrint(scope.row.base64EncodeContent,scope.row.trackingNo,scope.row.isPrint)" type="text" size="small" v-if="scope.row.orderStatus==3" icon="el-icon-printer" v-loading.fullscreen.lock="fullscreenLoading">打印面单</el-button>
                          <el-button @click="cancelFahuo(scope.row.orderId,scope.row.supplierId,scope.row.wlOrderId)" type="text" size="small" v-if="scope.row.orderStatus==3&&scope.row.base64EncodeContent!=null">取消发货</el-button>
                          <!-- <el-button @click="openRefundTk(scope.row.orderId,scope.row.totalPrice,scope.row.out_trade_no)" type="text" size="small" v-if="scope.row.orderStatus==5&&scope.row.afterStatus==1">同意退款</el-button>
                          <el-button @click="openTip(scope.row.orderId,8)" type="text" size="small" v-if="scope.row.orderStatus==5&&scope.row.afterStatus==1">拒绝退款</el-button> -->
                        </template>
                        </el-table-column>
                    </el-table>
                    <pagination
                    :total="total"
                    :limit="pageSize"
                    :page="pageNumber"
                    :pageSize="pageSize"
                    @pageChange="pageChange"
                    ></pagination>
                </div>
            </div>
        </div>
        <logistics-box
          ref="logisticsBox"
        ></logistics-box>
        <order-desc
          ref="orderDesc"
        ></order-desc>
        <tips-box
          ref="tipsBox"
          @confirmTip="confirmTip"
        ></tips-box>
        <input-popup
          ref="inputPopup"
          @confirmTip="confirmRefund"
        ></input-popup>
    </div>
</template>
<script>
import Pagination from "@/components/pagination.vue";
import logisticsBox from "@/components/logisticsBox.vue";
import orderDesc from "@/components/orderDesc.vue";
import tipsBox from "@/components/tipsBox.vue";
import inputPopup from "@/components/inputPopup.vue";
import printJS from 'print-js';
import JSZip from 'jszip';
import { saveAs } from 'file-saver';
export default {
    components: {
    Pagination,
    logisticsBox,
    orderDesc,
    tipsBox,
    inputPopup
  },
  data() {
    return {
      dialogVisible:true,
      accountType:0,
      accountId:0,
      total: 0,
      pageSize: 30,
      pageNumber: 1,
      tableData: [],
      boxIsShow:false,
      searchForm:{
        orderId:'',
        orderStatus:'0',
        trackingNo:'',
        createTime:'',
        createTime1:'',
        createTime2:'',
        downloadTime:'',
        downloadTime1:'',
        downloadTime2:'',
        getPdfTime:'',
        getPdfTime1:'',
        getPdfTime2:'',
        isDownload:''
      },
      editForm:{
        orderId:'',
        orderStatus:1
      },
      refundForm:{
        orderId:'',
        orderTotal:0,
        out_trade_no:''
      },
      multipleSelection: [],
      choiceIds:'',
      fullscreenLoading: false
    };
  },
  methods: {
    __init() {
      this.accountType=Number(sessionStorage.getItem("supplierType"));
      this.accountId=Number(sessionStorage.getItem("supplierId"));
      this.getData();
    },
    getData(){
      var url="manager/getOrdersByPage";
      var params={
        accountType: this.accountType,
        accountId:this.accountId,
        orderId:this.searchForm.orderId,
        orderStatus:this.searchForm.orderStatus,
        orderTime1:this.searchForm.createTime1,
        orderTime2:this.searchForm.createTime2,
        getPdfTime1:this.searchForm.getPdfTime1,
        getPdfTime2:this.searchForm.getPdfTime2,
        downloadTime1:this.searchForm.downloadTime1,
        downloadTime2:this.searchForm.downloadTime2,
        isDownload:this.searchForm.isDownload,
        trackingNo:this.searchForm.trackingNo,
        pageSize:this.pageSize,
        pageNum:this.pageNumber,
      }
      this.$post(url, params).then((res) => {
        console.log(res)
        if (res.code === 0) {
          this.tableData=res.data.list;
          this.total=res.data.total;
        } else {
          this.$message.error(res.msg)
        }
      });
    },
    handleDateChange1(dates){
      if (dates) {
        this.searchForm.getPdfTime1=dates[0];
        this.searchForm.getPdfTime2=dates[1];
      }
    },
    handleDateChange2(dates){
      if (dates) {
        this.searchForm.downloadTime1=dates[0];
        this.searchForm.downloadTime2=dates[1];
      }
    },
    handleDateChange3(dates){
      if (dates) {
        this.searchForm.createTime1=dates[0];
        this.searchForm.createTime2=dates[1];
      }
    },
    resetForm() {
      this.searchForm={
        orderId:'',
        orderStatus:'0',
        trackingNo:'',
        createTime:'',
        createTime1:'',
        createTime2:'',
        downloadTime:'',
        downloadTime1:'',
        downloadTime2:'',
        getPdfTime:'',
        getPdfTime1:'',
        getPdfTime2:'',
        isDownload:''
      }
      this.pageNumber =1;
      this.getData();
    },
    handleSelect(key, keyPath){
      console.log(key, keyPath);
      this.searchForm.orderStatus=key;
      this.pageNumber =1;
      this.getData();
    },
    pageChange(e) {
      console.log(e)
      this.pageNumber = e.page;
      this.getData();
    },
    search(){
      this.pageNumber=1;
      this.getData();
    },
    lookLogistics(trackingNo,supplierId){
      if (this.$refs.logisticsBox) {
        // 显示当前详情
        this.$refs.logisticsBox.tkIsShow = true;
        this.$refs.logisticsBox.title = "物流信息";
        this.$refs.logisticsBox.__init(trackingNo,supplierId);
      }
    },
    toDesc(orderId){
      if (this.$refs.orderDesc) {
        // 显示当前详情
        this.$refs.orderDesc.tkIsShow = true;
        this.$refs.orderDesc.title = "订单详情";
        this.$refs.orderDesc.__init(orderId);
      }
    },
    confirmTip(){
      this.changeOstatus();
    },
    openTip(orderId,state){
      this.editForm={
        orderId:orderId,
        orderStatus:state
      }
      var tipContent="";
      if(state==3){
        tipContent="确定为其执行发货操作吗？"
      }else if(state==7){
        tipContent="您确定同意执行退款操作吗？"
      }else if(state==8){
        tipContent="您确定不同意执行退款操作吗？"
      } 
      if (this.$refs.tipsBox) {
        // 显示当前详情
        this.$refs.tipsBox.tkIsShow = true;
        this.$refs.tipsBox.title = "温馨提示";
        this.$refs.tipsBox.tipContent=tipContent;
      }
    },
    changeOstatus(){
      const loading = this.$loading({
          lock: true,
          text: '正在操作中，请稍等',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
      });
      if (this.$refs.tipsBox) {
        this.$refs.tipsBox.tkIsShow = false;
      }
      var url="userApi/updateOrderStatus";
      var params={
        orderId:this.editForm.orderId,
        orderStatus:this.editForm.orderStatus
      }
      this.$post(url, params).then((res) => {
        console.log(res)
        loading.close();
        if (res.code === 0) {
          if(res.data===1){
            this.$message.success("执行成功")
            this.getData();
          }else{
            this.$message.error("系统异常，请稍后再试")
          }
        } else {
          this.$message.error(res.msg)
        }
      });
    },
    lookPdf(orderId){
      var url="manager/downloadPdf";
      var params={
        orderId:orderId
      }
      this.$post(url, params).then((res) => {
        console.log(res)
        if (res.code === 0) {
          window.open(res.data, '_blank');
        } else {
          this.$message.error(res.msg)
        }
      });
    },
    openRefundTk(orderId,orderTotal,out_trade_no){
      this.refundForm={
        orderId:orderId,
        orderTotal:orderTotal,
        out_trade_no:out_trade_no
      }
      if (this.$refs.inputPopup) {
        // 显示当前详情
        this.$refs.inputPopup.tkIsShow = true;
        this.$refs.inputPopup.title = "发起退款";
        this.$refs.inputPopup.inputValue=orderTotal;
      }
    },
    confirmRefund(value){
      console.log('接收到的退款金额:', value)
      // 这里可以添加金额验证逻辑（如：必须是数字、不能为负等）
      if (!this.validateAmount(value)) {
        return
      }
      var url="wxPay/applyRefund";
      var params={
        orderId:this.refundForm.orderId,
        refundTotal:value,
        out_trade_no:this.refundForm.out_trade_no
      }
      this.$post(url, params).then((res) => {
        console.log(res)
        if (res.code === 0) {
          this.$message.success("发起成功，正在退款")
        } else {
          this.$message.error(res.msg)
        }
      });
    },
    validateAmount(value) {
      if (!/^\d+(\.\d{1,2})?$/.test(value)) {
        this.$message.error('金额格式不正确')
        return false
      }
      return true
    },
    toPrint(url,trackingNo,isPrint){
      if(isPrint==1&&url!=''){
        printJS({
          printable: url, // PDF URL 或 Base64
          type: 'pdf',
          header: '电子面单',
          showModal: true // 显示打印预览弹窗
        });
      }else{
        this.fullscreenLoading = true;
        var url="manager/printWaybill";
        var params={
          trackingNo:trackingNo
        }
        this.$post(url, params).then((res) => {
          console.log(res)
          this.fullscreenLoading = false;
          if (res.code === 0) {
            printJS({
              printable: res.data, // PDF URL 或 Base64
              type: 'pdf',
              header: '电子面单',
              showModal: true // 显示打印预览弹窗
            });
          } else {
            this.$message.error(res.msg)
          }
        });
      }
    },
    cancelFahuo(orderId,supplierId,wlOrderId){
      const loading = this.$loading({
          lock: true,
          text: '正在操作中，请稍等',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
      });
      var url="manager/cancelWuliuOrder";
      var params={
        orderId:orderId,
        supplierId:supplierId,
        wlOrderId:wlOrderId
      }
      this.$post(url, params).then((res) => {
        console.log(res)
        loading.close();
        if (res.code === 0) {
            this.$message.success("执行成功")
            this.getData();
        } else {
          this.$message.error(res.msg)
        }
      });
    },
    handleSelectionChange(val){
      this.multipleSelection = val;
      if(val){
        const choiceIds = val.map(item => item.orderId).join(';');
        this.choiceIds=choiceIds;
        console.log(choiceIds)
      }
      console.log(val)
    },
    BatchGetTNo(){
      if(this.multipleSelection.length<=0){
        this.$message.error("请先选择要操作的订单")
        return;
      }
      var url="manager/batchGetTrackingNo";
      var params={
        orderId:this.choiceIds
      }
      this.$message.success("正在获取，稍后刷新查看")
      this.$post(url, params).then((res) => {
        console.log(res)
        // if (res.code === 0) {
        //     this.$message.success("执行成功")
        //     this.getData();
        // } else {
        //   this.$message.error(res.msg)
        // }
      });
    },
    BatchDownload(){
      this.fullscreenLoading = true;
      var url="manager/batchDownloadPdf";
      var params={
        orderId:this.choiceIds
      }
      this.$post(url, params).then((res) => {
        console.log(res.data)
        this.downloadAsZip(res.data);
      });
    },
    async downloadAsZip(urls) {
      const zip = new JSZip();
      
      try {
        // 并行获取文件并保留文件名
        const fetchPromises = urls.map(url => {
          // 提取原始文件名（处理含路径/参数的URL）
          const fileName = url.split('/').pop().split('?')[0].split('#')[0];
          return fetch(url)
            .then(res => res.blob())
            .then(blob => ({ blob, fileName })); // 返回文件名和Blob对象
        });
        
        const files = await Promise.all(fetchPromises);
        
        // 添加文件到 ZIP（保留原始名）
        files.forEach(({ blob, fileName }) => {
          zip.file(fileName, blob);
        });
        
        // 生成并保存 ZIP
        const zipBlob = await zip.generateAsync({ type: 'blob' });
        const timestampSec = Math.floor(Date.now() / 1000);
        saveAs(zipBlob, '产物_'+timestampSec+'.zip');
        this.fullscreenLoading = false;
      } catch (error) {
        console.error('下载失败:', error);
        this.fullscreenLoading = false;
      }
    }
  }
}
</script>
<style scoped lang="scss">
  .common-box{
    background-color: #f9f9fb;
    height: 100%;
  }
  .common-content-box{
    height: 95%;
    margin-top: 2%;
    width: 96%;
    display: inline-block;
  }
  .content-table-box{
    background-color: #fff;
    width: 100%;
    height: 100%;
    border-radius: 5px;
    box-shadow: 0 0 5px 1px rgba(83, 83, 83, 0.1);
  }
  .content_table_title_box{
    position: relative;
    height: 30px;
    margin-top: 10px;
    width: 100%;
    display: inline-block;
  }
  .content_table_title_icon{
    position: absolute;
    left: 15px;
    height: 18px;
    top: 6px;
  }
  .content_table_title{
    position: absolute;
    line-height: 34px;
    height: 100%;
    font-size: 15px;
    color: #42484e;
    left: 40px;
  }
  .table_search_box{
    text-align: left;
    margin-top: 10px;
    margin-left: 2%;
  }
  .table_box{
    height: calc(100% - 255px);
    margin-top: 10px;
    width: 96%;
    margin-left: 2%;
  }
  .line-break span{
    display: block;
  }
  .gn_btn_div{
    margin: 10px 0px;
    width: 96%;
    margin-left: 2%;
    text-align: left;
  }
</style>